package com.hgk.common.common.ui.activity;

import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import com.common.dongqiuhui.apps.comm.tools.BallUtil;
import com.common.dongqiuhui.apps.comm.util.SharedPreferencesUtil;
import com.common.nostra13.universalimageloader.core.ImageLoader;
import com.hgk.common.common.ui.activity.listener.PlayingTitleListener;
import com.hgk.common.common.ui.view.BallTitleView;
import com.hgk.common.common.util.UiSettingUtil;

import java.lang.reflect.Field;

import width.hgk.wanwan.R;

/**
 * 带标题栏的activity
 * 
 * @author fyh
 * 
 */
public abstract class BallTitleAcitivty extends BallActivity implements
		PlayingTitleListener, OnClickListener {
    public BallTitleView getViewTitle() {
        return viewTitle;
    }

    /**
	 * 自定义标题栏View
	 */
	protected BallTitleView viewTitle;
	/**
	 * body
	 */
	protected View viewBody;
	/**
	 * 身体的布局
	 */
	protected RelativeLayout relativelayout;

	private PlayingTitleListener listener;

	private RelativeLayout relativelayout_right;
	private RelativeLayout relativelayout_left;
	private RelativeLayout mMengceng; /* 蒙层 */

	private ProgressDialog mDialog;
	private int layoutId = 0;

    public View getmTopView() {
        return mTopView;
    }

    protected  View mTopView;
	// 无网络刷新
	public Button getmRefreshButton() {
		return viewTitle.getmRefreshButton();
	}
	public Button getmRefreshNoDateButton() {
		return viewTitle.getmRefreshNoDateButton();
	}

	public void startmAnim() {
		viewTitle.startAnim();
	}

	public void stopmAnim() {
		viewTitle.stopAnim();
	}

	// 加载页面
	public LinearLayout getLoadingView() {
		return viewTitle.getLoadingView();
	}

	public void showNoDataView(){
		if (viewTitle.getNodataView().getVisibility() == View.GONE) {
			viewTitle.getNodataView().setVisibility(View.VISIBLE);
		}
	}
	public void hideNodataView(){
		if (viewTitle.getNodataView().getVisibility() == View.VISIBLE) {
			viewTitle.getNodataView().setVisibility(View.GONE);
		}
	}
    public void showNetView(){
    	if (viewTitle.getNetView().getVisibility() == View.GONE) {
			viewTitle.getNetView().setVisibility(View.VISIBLE);
		}
    }
    public void hideNetView(){
    	if (viewTitle.getNetView().getVisibility() == View.VISIBLE) {
			viewTitle.getNetView().setVisibility(View.GONE);
		}
    }
	public void showLoadingView() {
		
		if (viewTitle.getLoadingView().getVisibility() == View.GONE) {
			startmAnim();
			viewTitle.getLoadingView().setVisibility(View.VISIBLE);
		}
	}

	public void hideLoadingView() {
		if (viewTitle.getmAnim() != null) {
			viewTitle.getmAnim().stop();
		}
		if (viewTitle.getLoadingView().getVisibility() == View.VISIBLE) {
			viewTitle.getLoadingView().setVisibility(View.GONE);
		}

	}

	// 无数据View
	public View getNodataView() {
		return viewTitle.getNodataView();
	}

	// 无网络数据View
	public View getNetView() {
		return viewTitle.getNetView();
	}

	// 设置无数据时的显示文案
	public void setNetdata(String content1, String content2) {
		if (!TextUtils.isEmpty(content1)) {
			viewTitle.getNet_tv1().setVisibility(View.VISIBLE);
			viewTitle.getNet_tv1().setText(content1);
		} else {
			viewTitle.getNet_tv1().setVisibility(View.GONE);
		}
		if (!TextUtils.isEmpty(content2)) {
			viewTitle.getNet_tv2().setText(content2);
			viewTitle.getNet_tv2().setVisibility(View.VISIBLE);
		} else {
			viewTitle.getNet_tv2().setVisibility(View.GONE);
		}
	}

	public void setButton(String text){
		Button btn=(Button) findViewById(R.id.freflush_net_btn);
		btn.setText(text);
	}

	// 设置无数据时的显示文案
	public void setNodata(String content1, String content2) {
		if (!TextUtils.isEmpty(content1)) {
			viewTitle.getNodata_tv1().setVisibility(View.VISIBLE);
			viewTitle.getNodata_tv1().setText(content1);
		} else {
			viewTitle.getNodata_tv1().setVisibility(View.GONE);
		}
		if (!TextUtils.isEmpty(content2)) {
			viewTitle.getNodata_tv2().setVisibility(View.VISIBLE);
			viewTitle.getNodata_tv2().setText(content2);
		} else {
			viewTitle.getNodata_tv2().setVisibility(View.GONE);
		}
	}

	// 无数据内容一
	public TextView getNodataContent1() {
		return viewTitle.getNodata_tv1();
	}

	// 无数据内容二
	public TextView getNodataContent2() {
		return viewTitle.getNodata_tv2();
	}

	// 无网络内容一
	public TextView getNetContent1() {
		return viewTitle.getNet_tv1();
	}

	// 无网络内容二
	public TextView getNetContent2() {
		return viewTitle.getNet_tv2();
	}

	// 无数据图片
	public ImageView getNodataImage() {
		return viewTitle.getNodata_img();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		babytreecloselistener = this;
		super.onCreate(savedInstanceState);
		try {
			init();
			listener = this;
			viewTitle = new BallTitleView(this);
			viewTitle.setLayoutParams(new LayoutParams(
					LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
			mMengceng = viewTitle.getRelativeLayoutMengCeng();
			relativelayout_right = viewTitle.getRelativeLayoutForRight();
			int right_view_id = getViewForButtonRight();
			if (right_view_id != 0) {
				View view = LayoutInflater.from(this).inflate(right_view_id,
						null);
				relativelayout_right.addView(view);
			}
			relativelayout_left = viewTitle.getRelativeLayoutForLeft();
			int left_view_id = getViewForButtonLeft();
			if (left_view_id != 0) {
				View view = LayoutInflater.from(this).inflate(left_view_id,
						null);
				relativelayout_left.addView(view);
			}
			setContentView(viewTitle);
		} catch (OutOfMemoryError e) {
			e.printStackTrace();
			System.gc();
			ImageLoader.getInstance().clearMemoryCache();
		}
		if (listener == null) {
			return;
		}
		Button buttonLeft = viewTitle.getButton_left();
		RelativeLayout relativeLeft = viewTitle.getRelativelayout_left();
		relativeLeft.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
        buttonLeft.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
		Button buttonRight = viewTitle.getButton_right();
		RelativeLayout relativeRight = viewTitle.getRelativelayout_right();
		relativeRight.setOnClickListener(this);
		buttonRight.setOnClickListener(this);

		UiSettingUtil.setActivityTitle(viewTitle.getTextView(),
				listener.getTitleString());

		LinearLayout linearlayout = viewTitle.getLinearlayout();

		listener.setTitleView(linearlayout);
		listener.setLeftButton(relativeLeft,buttonLeft);
		listener.setRightButton(relativeRight,buttonRight);
		if (!TextUtils.isEmpty(buttonRight.getText().toString())
				|| !TextUtils.isEmpty(buttonRight.getText().toString())) {
			buttonRight.setVisibility(View.VISIBLE);
		}

		relativelayout = viewTitle.getRelativeLayout();
		relativelayout.setBackgroundColor(0xfff1f1f1);
		layoutId = listener.getBodyView();
		if (layoutId == 0) {
			return;
		}
		try {
			viewBody = LayoutInflater.from(this).inflate(layoutId, null);
			viewBody.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
					LayoutParams.FILL_PARENT));
		} catch (OutOfMemoryError e) {
			e.printStackTrace();
			ImageLoader.getInstance().clearMemoryCache();
			System.gc();
		}
		if (viewBody != null) {
			relativelayout.addView(viewBody);
		}
		TranslucentStatus(getResources().getColor(R.color.btncolor));
		dispathOnclik();
		getmRefreshButton().setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                showLoadingView();
                noNetReflushBtn();
            }

        });
		getmRefreshNoDateButton().setOnClickListener(this);
	}

	/**
	 * 该方法适用于继承与BabyTreeTitleActivity没有使用ViewTitle的页面,并且希望自定义布局在状态栏之下
	 * 根据父布局不同而传入LayoutParams
	 * @param view
	 * @param Params
	 */
	public void TranslucentStatus(View view ,LayoutParams Params){
		if (android.os.Build.VERSION.SDK_INT > 18) {
			view.setLayoutParams(Params);
		}
	}
	/**
	 * 颜色加深处理
	 *
	 * @param RGBValues
	 *            RGB的值，由alpha（透明度）、red（红）、green（绿）、blue（蓝）构成，
	 *            Android中我们一般使用它的16进制，
	 *            例如："#FFAABBCC",最左边到最右每两个字母就是代表alpha（透明度）、
	 *            red（红）、green（绿）、blue（蓝）。每种颜色值占一个字节(8位)，值域0~255
	 *            所以下面使用移位的方法可以得到每种颜色的值，然后每种颜色值减小一下，在合成RGB颜色，颜色就会看起来深一些了
	 * @return
	 */
	public int colorBurn(int RGBValues) {
		int alpha = RGBValues >> 24;
		int red = RGBValues >> 16 & 0xFF;
		int green = RGBValues >> 8 & 0xFF;
		int blue = RGBValues & 0xFF;
		red = (int) Math.floor(red * (1 - 0.1));
		green = (int) Math.floor(green * (1 - 0.1));
		blue = (int) Math.floor(blue * (1 - 0.1));
		return Color.rgb(red, green, blue);
	}
	/**
	 * 该方法适用于使用viewtTitlebar的页面
	 * @param mColor 16进制的颜色值参数
	 *
	 */
	public  void TranslucentStatus(int mColor){
		if (android.os.Build.VERSION.SDK_INT > 18) {
			//设置根布局的内边距
			viewTitle.setPadding(0, getStatusBarHeight(), 0, 0);
			mTopView = new View(this);
			LinearLayout.LayoutParams lParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, getStatusBarHeight());
			mTopView.setBackgroundColor(mColor);
			mTopView.setLayoutParams(lParams);
			// 获得根视图并把mTopView加进去。
			ViewGroup view = (ViewGroup) getWindow().getDecorView();
			view.addView(mTopView);
		}
	}
	public void RemoveTopView(){
		if (android.os.Build.VERSION.SDK_INT > 18)
		{
			viewTitle.setPadding(0, 0, 0, 0);
			ViewGroup currView = (ViewGroup) getWindow().getDecorView();
			if (mTopView!=null)
			{
				currView.removeView(mTopView);
			}
		}

	}
	/**
	 * 获取状态栏颜色
	 *
	 * @return
	 */
	public int getStatusBarHeight() {
		Class<?> c = null;
		Object obj = null;
		Field field = null;
		int x = 0, statusBarHeight = 0;
		try {
			c = Class.forName("com.android.internal.R$dimen");
			obj = c.newInstance();
			field = c.getField("status_bar_height");
			x = Integer.parseInt(field.get(obj).toString());
			statusBarHeight = getResources().getDimensionPixelSize(x);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return statusBarHeight;
	}

	/**
	 * 设置标题栏右侧按钮的view
	 */
	public int getViewForButtonRight() {

		return 0;
	}

	/**
	 * 设置标题栏左侧按钮的view
	 * 
	 */
	public int getViewForButtonLeft() {

		return 0;
	}

	/**
	 * 获取标题栏右侧的布局
	 * 
	 * @return
	 */
	public RelativeLayout getRelativeLayoutForButtonRight() {

		return relativelayout_right;
	}

	/**
	 * 初始化
	 * 
	 * @author wangshuaibo
	 */
	protected void init() {

	}

	public void addViewBody(View view) {
		if (view != null)
			relativelayout.addView(view);
	}

	/**
	 * 替换viewBody
	 * 
	 * @param view
	 */
	public void cleanViewBody(View view) {
		if (viewBody != null) {
			relativelayout.removeAllViews();
			viewBody = null;
		}
		viewBody = view;
		relativelayout.addView(viewBody);
		relativelayout.setVisibility(View.VISIBLE);
	}

	/**
	 * 替换bady布局
	 * 
	 * @param view
	 * @author wangbingqi
	 */
	public void cleanBadyView(View view) {
		relativelayout.removeAllViews();
		relativelayout.addView(view);
	}

	/**
	 * 清楚bady
	 */
	public void cleanBadyView() {
		relativelayout.removeAllViews();
	}

	/**
	 * 替换bady布局
	 * 
	 * @param id
	 * @author wangbingqi
	 */
	public void cleanBadyView(int id) {
		relativelayout.removeAllViews();
		View view = LayoutInflater.from(this).inflate(id, null);
		relativelayout.addView(view);
	}

	/**
	 * 获取右边Button
	 * 
	 * @author wangshuaibo
	 * @return
	 */
	public Button getRightButton() {
		return viewTitle.getButton_right();
	}

	/**
	 * 获取左边Button
	 * 
	 * @author wangshuaibo
	 * @return
	 */
	public Button getLeftButton() {
		return viewTitle.getButton_left();
	}

	/**
	 * 动态设置标题名字
	 * 
	 * @param str
	 * @author luozheng
	 */
	public void cleanTitleString(String str) {
		viewTitle.getTextView().setText(str);
	}
	public void cleanRightButtonText(String str){
		viewTitle.getButton_right().setText(str);
	}
	/**
	 * 动态设置标题名字
	 * 
	 */
	public void cleanTitleString2(String html) {
		viewTitle.getTextView().append(html);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		// if (view != null) {
		// view.removeAllViews();
		// view = null;
		// }
	}

	public void showDialog() {
		if (mDialog == null) {
			mDialog = new ProgressDialog(this, R.style.processDialog);
		}
		// mDialog.setTitle(title);
		// mDialog.setMessage(content);
		// mDialog.setCancelable(cancelable);
		mDialog.show();
	}
	 public void disDialog(){
		 if(mDialog!=null&&mDialog.isShowing()){
			 mDialog.dismiss();
		 }
	 }

	public void setTitleView(LinearLayout linearlayout) {
	}

	//
	public void hideTitleBar() {
		viewTitle.getFramelayout().setVisibility(View.GONE);
	}

    /**
     * 得到头部View
     */

    public FrameLayout getTitleView(){
        return viewTitle.getFramelayout();
    }

    /**
     * 得到标题栏textview
     */
    public TextView getTitleTv(){
        return viewTitle.getTitleTv();
    }
	// 无网络刷新按钮事件
	public void noNetReflushBtn() {

	}


	/**
	 * 设置蒙层
	 * 
	 * @param mcView
	 *            蒙层布局
	 * @param mcKey
	 *            蒙层唯一识别的key
	 * @param isNeedNet
	 *            是否需要联网判断
	 */
	public boolean showMengCeng(int mcView, final String mcKey, boolean isNeedNet) {

		if (isNeedNet && !BallUtil.hasNetwork(mContext)) {
			return false;

		}
		if (mcView != 0 && isShowMC(mcKey)) {
			try {
				View view = LayoutInflater.from(this).inflate(mcView, null);
				ViewGroup.LayoutParams param = new ViewGroup.LayoutParams(
						ViewGroup.LayoutParams.FILL_PARENT,
						ViewGroup.LayoutParams.FILL_PARENT);
				mMengceng.setVisibility(View.VISIBLE);
				mMengceng.removeAllViews();
				mMengceng.addView(view, param);
				view.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						mMengceng.setVisibility(View.GONE);
						SharedPreferencesUtil.setValue(getApplicationContext(),
								mcKey, 1);
					}
				});
				return true;

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return false;

	}

	/**
	 * 是否显示蒙层
	 * 
	 * @param Key
	 * @return
	 */
	private boolean isShowMC(String Key) {
		if (TextUtils.isEmpty(Key)) {
			return false;
		} else if (SharedPreferencesUtil.getIntValue(this, Key) == -1) {
			return true;
		} else {
			return false;
		}
	}

	// 屏幕点击时间
	private void dispathOnclik() {
		getLoadingView().setOnClickListener(this);
		getNetView().setOnClickListener(this);
		getNodataView().setOnClickListener(this);
	}
}

